package com.qianfeng.openplatform.geteway.fiter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.openplatform.commons.field.RedisKeyPrefix;
import com.qianfeng.openplatform.commons.field.util.AppTowCacheUtil;
import com.qianfeng.openplatform.geteway.client.CacheClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * @author 江江
 * @Date 2020/7/24 14:03
 */
@Component
public class GateWayFilter extends ZuulFilter {//过滤
    @Autowired
    private CacheClient cacheClient;

    @Override
    public String filterType() { //指定当前过滤器的类型
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() { //指定过滤器的执行顺序
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 5;
    }

    @Override
    public boolean shouldFilter() {// 开启当前过滤器
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override // 测试数据http://localhost:9876/openapi?method=servertest01
    public Object run() throws ZuulException {
        //指定过滤器中的具体业务代码
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
       // System.out.println("request值为: " + request);
        String method = request.getParameter("method");
      //  System.out.println("method值为: " + method);
        if (!StringUtils.isEmpty(method)) {
            try {
//                从redis中获取
          //      Map<Object, Object> objectMap = cacheClient.hGetAll(RedisKeyPrefix.WEB_MASTER_API_MAPPING_HASH_PRE + method);//请求头

                //从项目缓存中获取
                Map<Object, Object> objectMap = AppTowCacheUtil.cacheRoutingMap.get(RedisKeyPrefix.WEB_MASTER_API_MAPPING_HASH_PRE + method);
                if (objectMap==null){
                    objectMap = cacheClient.hGetAll(RedisKeyPrefix.WEB_MASTER_API_MAPPING_HASH_PRE + method);
                    AppTowCacheUtil.cacheRoutingMap.put(RedisKeyPrefix.WEB_MASTER_API_MAPPING_HASH_PRE + method,objectMap);
                    System.out.println("GateWayFilter:61行:  从redis中获取的值....");
                }else{
                    System.out.println("GateWayFilter:63行:  从缓存中获取的值........");
                }


                if (objectMap != null) {
                    String url = (String) objectMap.get("insideapiurl");
                    String serviceid = (String) objectMap.get("serviceid");

                    //http://localhost:9876/openapi/jiangruiqi?method=servertest02
                    //http://localhost:9876/openapi?method=servertest04&name=jiangruiqi
                    //获得浏览器输入的真实地址
                   // System.out.println("request.getRequestURI(): " + request.getRequestURI() + "---------------");//request.getRequestURI(): /openapi/jiangruiqi---------------
                    String uri = request.getRequestURI();
                    if (!"/openapi".equals(uri)) {
                        String restParam = uri.replaceAll("/openapi", "");//将uri /openapi替换成""
                        // url.matches()// 以斜杠 中间出现数字下划线和 {
                        url = url.substring(0, url.indexOf("/{")) + restParam;

                    }
                    requestContext.put(FilterConstants.SERVICE_ID_KEY, serviceid);
                    requestContext.put(FilterConstants.REQUEST_URI_KEY, url);

                    Set<Object> keys = objectMap.keySet();
                    for (Object key : keys) {
                        Object v = objectMap.get(key);
                       // System.out.println(key + "------>" + v);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            requestContext.setSendZuulResponse(false);//拦截响应
            requestContext.setResponseStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());

        }
        return null;
    }
}
